/*
 * @LastEditTime: 2023-02-28 11:30:54
 */
import { Music } from "../Models/Music.schema";
import { createMusicDTO, updateMusicDTO } from "../DTO/Music.dto";
import { isExistsforId, isExistsforTitle } from "../hook";
import Axios from 'axios'
// import { getMusicUrl } from "../../request/api/api_music";
// import request from "../../request/request";
export class MusicController {
  constructor(private readonly musicModel: typeof Music) { }

  /**
   * 创建歌曲
   * @param dto 数据传输对象
   * @returns 返回创建对象
   */
  async createItem(dto: createMusicDTO) {
    try {
      return {
        code: 200,
        message: "创建成功",
        data: await this.musicModel.create(dto),
      };
    } catch (error) {
      return await error;
    }
  }
  /**
   * 以ID为查找依据删除歌曲
   * @param id 要删除元素的唯一ID
   * @returns
   */
  async removeById(id: string) {
    try {
      if (!await isExistsforId(id, this.musicModel)) {

        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "删除成功",
          data: await this.musicModel.deleteOne({ _id: id }),
        };
      }
    } catch (error) {
      return await error;
    }
  }

  /**
   * 按ID更新歌曲
   * @param id 要更新的ID
   * @param dto  要更新的内容
   * @returns 更新对象
   */
  async updateById(id: string, dto: updateMusicDTO) {
    try {
      if (!!await isExistsforId(id, this.musicModel)) {
        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "更新成功",
          data: await this.musicModel.updateOne({ _id: id }, dto),
        };
        console.log(1)
      }
    } catch (error) {
      return await error;
    }
  }

  /**
   * 按歌曲名称查找歌曲
   * @param title 要查找的歌曲名称
   * @returns 查询对象
   */
  async findByTitle(title: string) {
    try {
      const reg = new RegExp(`${title}`, 'g');
      if (!await isExistsforTitle(title, this.musicModel)) {
        //网易云查询
        const data = await Axios.get(`http://162.14.104.16:3005/search?keywords=${title}}&type=1&limit=100`, { withCredentials: true })
        const res = await data.data as {
          code: number;
          result: {
            searchQcReminder: any;
            songCount: number;
            songs: {
              id: string;//歌曲id
              name: string;
              picUrl: string; // 封面
              ar: any; //艺术家
              al: {
                picUrl: string;//封面地址
                id: string;//封面id
                name: string;// 专辑名
              };  //专辑
              dt: string;//时长
            }[];
          }
        };
        // 只录入前10条数据
        //  al 专辑信息
        // ar 演唱者数组
        if (res.result.songCount > 0) {
          for (let i = 0; i < res.result.songs.length; i++) {
            if (i === 40) { break; }
            let tempData = {
              //歌曲唯一标识
              _id: res.result.songs[i].id,
              //歌曲名称
              name: res.result.songs[i].name,
              //封面
              cover: res.result.songs[i].al.picUrl,
              singer: res.result.songs[i].ar,
              //歌词唯一标识
              lyricsId: res.result.songs[i].id,
              //所属专辑唯一标识 
              album: res.result.songs[i].al,
              //播放地址
              link: res.result.songs[i].id,
              //时长
              time: res.result.songs[i].dt,
            } as createMusicDTO
            // this.createItem()

            // console.log();
            // 添加到数据库
            // console.log(tempData);
            await this.createItem(tempData);
          }
          return {
            code: 200,
            message: '查询成功',
            data: await this.musicModel.find({ name: reg }),
          }
        }
        return {
          code: 400,
          message: '不存在查询的Title',
        }
      } else {
        return {
          code: 200,
          message: "查询成功",
          data: await this.musicModel.find({ name: reg }),
        };
      }
    } catch (error) {
      return await error;
    }
  }

  /**
   * 按ID查找歌曲
   * @param id 要查找的歌曲名称
   * @returns 查询对象
   */
  async findById(id: string) {
    try {
      if (!await isExistsforId(id, this.musicModel)) {

        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "查询成功",
          data: await this.musicModel.find({ _id: id }),
        };
      }
    } catch (error) {
      return false;
    }
  }
  //查询全部数据
  async findAll() {
    try {
      if (await this.musicModel.find().count() != 0)
        return {
          code: 200,
          message: "查询成功",
          data: await this.musicModel.find(),
        };
      else
        return {
          code: 400,
          message: "该数据集不存在数据"
        }
    }
    catch (error) {
      return await error;
    }
  }
  // 获取歌曲播放链接
  async findLinkById(id: string) {
    try {
      const data = await Axios.get(`http://162.14.104.16:3005/song/url?id=${id}`, { withCredentials: true })
      if (data.data) {
        return {
          code: 200,
          message: '查询成功',
          data: data.data,
        }
      }
      else {
        return {
          code: 400,
          message: "查询失败"
        }
      }
    } catch (error) {
      return await error;
    }
  }
  // 检测音乐可用性
  async checkMusic(id: string) {
    try {
      const data = await Axios.get(`http://162.14.104.16:3005/check/music?id=${id}`, { withCredentials: true })
      if (data.data) {
        return {
          code: 200,
          message: '查询成功',
          data: data.data,
        }
      }
      else {
        return {
          code: 400,
          message: "查询失败"
        }
      }
    } catch (error) {
      return await error;
    }
  }
  //随机获取指定条数的数据
  async findBySize(size: number) {
    try {
      console.log(size)
      return {
        code: 200,
        message: "查询成功",
        data: await this.musicModel.aggregate([{ $sample: { size: size } }])
      }

    } catch (error) {
      return error;
    }
  }
  //获取新歌速递
  async findNewMusic(type: number) {
    try {
      console.log(typeof (type))
      console.log(type)
      const data = await Axios.get(`http://162.14.104.16:3005/top/song/?type=${type}`, { withCredentials: true })
      if (data) {
        const res = await data.data as {
          code: string,
          data: {
            album: any,
            lMusic: any,
            artists: any,
            name: string,
            id: string,
          }[];
        }
        // console.log(res)
        return {
          code: 200,
          message: '查询成功',
          data: res.data,
        }
      }
      else {
        return {
          code: 400,
          message: "查询失败"
        }
      }
    } catch (error) {
      return await error;
    }
  }
}
